package cn.wolfcode.crm.util;

import cn.wolfcode.crm.query.JSONResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice//Controller增强的注解
public class HandlerExceptionUtil {

    @ExceptionHandler(UnauthorizedException.class)
    public void handlerException(HandlerMethod method, HttpServletResponse response) throws IOException {
        ResponseBody anno = method.getMethodAnnotation(ResponseBody.class);
        /*如果是ajax请求则,就不能用跳转异常提示的那个界面了*/
        if(anno!=null){
            response.setContentType("application/json;charset=UTF-8");
            /*发送信息在弹出框中显示*/
            JSONResult result = new JSONResult();
            result.mark("您没有权限操作");
            response.getWriter().print(new ObjectMapper().writeValueAsString(result));
        }else{
            response.sendRedirect("/nopermission.jsp");
        }
    }
}
